package com.tn.socket;

import com.alibaba.fastjson.JSON;
import com.tn.controller.alarm.common.constants.SocketContants;
import com.tn.controller.alarm.common.enums.ActTypeEnum;
import com.tn.controller.alarm.common.model.cardrobot.CardSenderRobotInfoDO;
import com.tn.dao.cardsender.CardSenderRobotDao;
import com.tn.service.external.subsystem.GateRestfulService;
import com.tn.utils.SocketParamUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @ClassName SocketCommonHandle
 * @Description TODO
 * @Author Yezhongzhu
 * @Date 2021/12/30 16:48
 * @Version v1.0
 **/
@Component
@Slf4j
public class SocketCommonHandle {
    @Autowired
    private SocketProperties socketProperties;
    @Autowired
    private CardSenderRobotDao cardSenderRobotDao;
    @Autowired
    private GateRestfulService gateRestfulService;
    /*
    处理发卡机发来的报文信息
     */
    public String handle(String message,CardSendRobot cardSendRobot){
        String callback = "";
        Map<String,String> map = SocketParamUtil.formatParam(message);
        if(MapUtils.isEmpty(map)||StringUtils.isBlank(map.get(SocketContants.CardSendRobotField.ACT))){
            log.error("SocketCommonHandle map empty or ACT null error data:{}",message);
            return new StringBuilder("ERRCODE:1000;ERRMSG:none;").toString();
        }
        String act = map.get(SocketContants.CardSendRobotField.ACT);
        ActTypeEnum actTypeEnum = ActTypeEnum.getByCode(act);
        if(null==actTypeEnum){
            return new StringBuilder("ERRCODE:0;ERRMSG:none;ACK:").append(act).append(";").toString();
        }
        switch (actTypeEnum){
            //判断消息类型，并回传对应的报文
            case LOGIN:
                callback = actLogin(cardSendRobot, map);
                break;
            case SYNC_SETTING:
                callback = actSyncSetting(cardSendRobot, map);
                break;
            case RETURN_BACK:
                callback = actReturnBack(cardSendRobot, map,actTypeEnum);
                break;
            case HEARTBEAT:
                callback = actHeartbeat(cardSendRobot, map,actTypeEnum);
                break;
            case SYNC_BATTERY:
                callback = actSyncBattery(cardSendRobot, map,actTypeEnum);
                break;
            case POPUP_CONFIRM:
                callback = actPopupConfirm(cardSendRobot, map,actTypeEnum);
                break;
            case RENT_CONFIRM:
                callback = actRentConfirm(cardSendRobot, map,actTypeEnum);
                break;
            default:
                callback = actDefult(cardSendRobot, map,actTypeEnum);
                break;
        }
        return callback;
    }

    private String actDefult(CardSendRobot cardSendRobot, Map<String, String> map,ActTypeEnum actTypeEnum) {
        String callback = new StringBuilder("ERRCODE:0;ERRMSG:none;ACK:").append(actTypeEnum.getType()).append(";").toString();
        return callback;
    }

    private String actRentConfirm(CardSendRobot cardSendRobot, Map<String, String> map,ActTypeEnum actTypeEnum) {
        if(null==cardSendRobot){
            return null;
        }
        String orderId = map.get(SocketContants.CardSendRobotField.ORDERID);
        String id = map.get(SocketContants.CardSendRobotField.ID);//todo 校验id为000000000
        //todo 检测orderId跟id为空
        cardSendRobot.setWorkRunStatus(cardSendRobot.getSTATIONID(),true);
        cardSendRobot.setOrderMap(orderId,id);
//        setUsableBattery(cardSendRobot, map);
        String callback = new StringBuilder("ERRCODE:0;ERRMSG:none;ORDERID:").append(map.get(SocketContants.CardSendRobotField.ORDERID)).append(";ACK:").append(actTypeEnum.getType()).append(";").toString();
        return callback;
    }

    private String actPopupConfirm(CardSendRobot cardSendRobot, Map<String, String> map,ActTypeEnum actTypeEnum) {
        if(null==cardSendRobot){
            return null;
        }
        setUsableBattery(cardSendRobot, map);
        String callback = new StringBuilder("ERRCODE:0;ERRMSG:none;SLOT:").append(map.get(SocketContants.CardSendRobotField.SLOT)).append(";ACK:").append(actTypeEnum.getType()).append(";").toString();
        return callback;
    }

    private String actSyncBattery(CardSendRobot cardSendRobot, Map<String, String> map,ActTypeEnum actTypeEnum) {
        String callback = new StringBuilder("ERRCODE:0;ERRMSG:none;ACK:").append(actTypeEnum.getType()).append(";").toString();
        return callback;
    }

    private String actHeartbeat(CardSendRobot cardSendRobot, Map<String, String> map,ActTypeEnum actTypeEnum) {
        if(null==cardSendRobot){
            return null;
        }
        setUsableBattery(cardSendRobot, map);
        cardSendRobot.setReady(true);
        String callback = new StringBuilder("ERRCODE:0;ERRMSG:none;ACK:").append(actTypeEnum.getType()).append(";").toString();
        return callback;
    }

    private String actReturnBack(CardSendRobot cardSendRobot, Map<String, String> map,ActTypeEnum actTypeEnum) {
        String id = map.get(SocketContants.CardSendRobotField.ID);
        if(StringUtils.isNotBlank(id)){
            //解绑标签
            gateRestfulService.removeBinding(id);
        }
        String callback = new StringBuilder("ERRCODE:0;ERRMSG:none;ID:").append(id).append(";ACK:").append(actTypeEnum.getType()).append(";").toString();
        return callback;
    }

    private String actSyncSetting(CardSendRobot cardSendRobot, Map<String, String> map) {
        if(null==cardSendRobot){
            return null;
        }
        String stationid = map.get(SocketContants.CardSendRobotField.STATIONID);
        if(StringUtils.isNotBlank(stationid)){
            cardSendRobot.setSTATIONID(stationid);
        }
        setUsableBattery(cardSendRobot, map);
        String callback = new StringBuilder("TIME:").append(SocketParamUtil.getUnixTime()).append(";DOMAIN:").append(socketProperties.isUseInternet()?socketProperties.getInternetIp():SocketParamUtil.getInternetIp())
                .append(";IP:").append(socketProperties.isUseInternet()?socketProperties.getInternetIp():SocketParamUtil.getInternetIp()).append(";PORT:").append(socketProperties.getPort()).append(";BPS:30;CHECKUPDATEDELAY:1;SOFT_VER:81;")
                .append("FILE_NAME:null;HEARTBEAT:90;").toString();
        return callback;
    }

    private void setUsableBattery(CardSendRobot cardSendRobot, Map<String, String> map) {
        String useCount = map.get(SocketContants.CardSendRobotField.USABLE_BATTERY);
        if(StringUtils.isNotBlank(useCount)){
            try {
                int count = Integer.parseInt(useCount);
                cardSendRobot.setUSABLE_BATTERY(count);
            } catch (NumberFormatException e) {
                log.error("SocketCommonHandle setUsableBattery parseInt data:{} error:{}", JSON.toJSON(map),e.getMessage(),e);
            }
        }
    }

    private String actLogin(CardSendRobot cardSendRobot, Map<String, String> map) {
        //todo 根据mac地址查询stationid
        String mac = map.get(SocketContants.CardSendRobotField.MAC);
        CardSenderRobotInfoDO cardSenderRobotInfoDO = cardSenderRobotDao.queryStationId(mac);
        if(null==cardSenderRobotInfoDO){
            return "none";
        }
        cardSendRobot.setSTATIONID(cardSenderRobotInfoDO.getStationId());
        cardSendRobot.setTYPE(cardSenderRobotInfoDO.getType());
        cardSendRobot.setGATEIDNO(cardSenderRobotInfoDO.getGateIdNo());
        setUsableBattery(cardSendRobot, map);
        String callback = new StringBuilder("BINDADDRESS:1;STATIONID:").append(cardSenderRobotInfoDO.getStationId()).append(";").toString();
        return callback;
    }
}
